import * as React from "react";
import { observer } from "mobx-react";
import { observable } from "mobx";
import moment from "moment";
import {
  Row,
  Col,
  Button,
  Table,
  Modal,
  Form,
  Input,
  Select,
  Typography,
  Space,
  Spin,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import {
  deleteMenu,
  findParentSysMenu,
  addMenu,
  getfindAllMenu,
  updateMenu,
} from "../../../ServeApi";
import {
  listToTree,
  ergodicListAddKey,
  ergodicTree,
} from "../../../../../../utils/common";
import IconFont from "../../../../../../assets/ICON";
import "./index.less";
const { Option } = Select;
const { Text } = Typography;
export interface MenuTableProps {}

export interface MenuTableState {}

interface columnsDataCLass {
  title: string;
  dataIndex: string;
  render?: any;
  key: string;
}

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
    md: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
    md: { span: 16 },
  },
};
@observer
class MenuTable extends React.Component<MenuTableProps, MenuTableState> {
  @observable private columns: columnsDataCLass[] = [
    {
      title: "序号",
      dataIndex: "rank",
      key: "rank",
    },
    {
      title: "菜单名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "菜单模块",
      dataIndex: "pathName",
      key: "pathName",
    },
    {
      title: "父级编号",
      dataIndex: "parentId",
      key: "parentId",
    },
    {
      title: "菜单路径",
      dataIndex: "resUrl",
      key: "resUrl",
    },
    {
      title: "创建日期",
      dataIndex: "createTime",
      key: "createTime",
      render: (text) => {
        return <>{moment(text).format("YYYY-MM-DD")}</>;
      },
    },
    {
      title: "操作",
      dataIndex: "id",
      key: "id",
      render: (text, record) => {
        return (
          <>
            <Space size={26}>
              {record.pathName === "Index" ? null : (
                <span
                  style={{ color: "#595959", cursor: "pointer" }}
                  onClick={() => {
                    this.onEdit(record);
                  }}
                >
                  <IconFont
                    type="icon_form_bianji"
                    style={{ color: "#FBB10B" }}
                  />
                  <Text>编辑</Text>
                </span>
              )}

              {!record.children && text !== 50 ? (
                <span
                  style={{ color: "#595959", cursor: "pointer" }}
                  onClick={() => {
                    this.onDelete(record);
                  }}
                >
                  <IconFont
                    type="icon_form_shanchu"
                    style={{ color: "#FF6B6B" }}
                  />
                  <Text>删除</Text>
                </span>
              ) : null}
            </Space>
          </>
        );
      },
    },
  ];
  @observable private prentNode: any = [];
  @observable private isModalVisible: boolean = false;
  @observable private initValue: any = null;
  //add:新增，update:修改
  @observable protected Mod = "add";
  @observable private TableData: any = []; //直接进入table的树状数据
  @observable private listData: any = []; //请求接口来的原始数据
  private instance: any = null;
  state = { loading: false };
  render() {
    return (
      <>
        <div className="rowcon_body">
          <div>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                this.addMenuModal();
              }}
            >
              新增
            </Button>
          </div>
          <div className="rowcon_bottom"></div>
          <Spin spinning={this.state.loading}>
            <Table
              columns={this.columns}
              dataSource={this.TableData}
              pagination={false}
            ></Table>
          </Spin>
          <Modal
            title={this.Mod === "add" ? "新增菜单" : "编辑菜单"}
            visible={this.isModalVisible}
            onOk={() => {
              this.handleOk();
            }}
            onCancel={() => {
              this.handleCancel();
            }}
          >
            <Form {...formItemLayout} ref={(el) => (this.instance = el)}>
              <Row>
                <Col span={11} offset={1}>
                  <Form.Item
                    label="菜单序号："
                    name="rank"
                    rules={[
                      {
                        required: true,
                        message: "请填写菜单序号",
                      },
                      {
                        message: "菜单序号应为数字",
                        pattern: new RegExp(/^[0-9]\d*$/, "g"),
                      },
                    ]}
                  >
                    <Input placeholder="菜单序号" />
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item
                    label="菜单名称："
                    name="name"
                    rules={[
                      {
                        required: true,
                        message: "示例编号或者默认编号",
                      },
                    ]}
                  >
                    <Input placeholder="菜单名称" />
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item label="父级菜单：" name="parentId">
                    <Select defaultValue="">
                      {this.prentNode.map((item: any, index: number) => {
                        return (
                          <Option value={item.treeId} key={item.treeId}>
                            {item.name}
                          </Option>
                        );
                      })}
                      <Option value="">根目录</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item label="菜单图标：" name="resIon">
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item label="菜单模块：" name="pathName">
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={11} offset={1}>
                  <Form.Item label="菜单路径：" name="resUrl">
                    <Input />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Modal>
        </div>
      </>
    );
  }
  componentWillMount() {
    this.init();
  }
  init() {
    this.setState({ loading: true });
    this.asyngetPrentSysMenu();
    this.getData();
  }
  //获取父级菜单
  asyngetPrentSysMenu() {
    let _this = this;
    findParentSysMenu()
      .then((res: any) => {
        if (res.success) {
          _this.prentNode = res.data;
          _this.forceUpdate();
        }
      })
      .catch((err) => {});
  }
  //获取所有菜单
  async getData() {
    let _this = this;
    try {
      _this.setState({ loading: true });
      let res: any = await getfindAllMenu().catch((err) => {
        console.log(err);
        _this.setState({ loading: false });
      });
      let json: AjaxData = res;
      if (json.success) {
        _this.listData = json.data;
        _this.TableData = ergodicTree(listToTree(ergodicListAddKey(json.data)));
        _this.setState({ loading: false });
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  onEdit(item) {
    this.ifVisible();
    this.Mod = "update";
    setTimeout(() => {
      let pr = {
        name: item.name,
        rank: item.rank,
        parentId: item.parentId,
        treeId: item.treeId,
        resUrl: item.resUrl,
        pathName: item.pathName,
        resIon: item.resIon,
      };
      this.initValue = pr;
      if (this.instance) {
        const container: any = (this.instance as any) as HTMLDivElement;
        container.setFieldsValue(item);
      }
    });
  }
  async deleteMenuItem(item) {
    let _this = this;
    try {
      this.setState({ loading: true });
      const res: any = await deleteMenu(JSON.stringify(item));
      const json: AjaxData = res;
      if (json.success) {
        _this.setState({ loading: false });
        _this.init();
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk() {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (e) {
      Modal.error({
        title: `请求出错,请检查设备链接和网络情况。`,
      });
      _this.setState({ loading: false });
      console.error(e);
    }
  }
  async onDelete(item) {
    let pream = {
      menuId: item.treeId,
    };
    let _this = this;
    Modal.confirm({
      title: "是否确认删除菜单",
      onOk: () => {
        _this.deleteMenuItem(pream);
      },
    });
  }
  //新增菜单对话框
  addMenuModal() {
    this.Mod = "add";
    this.initValue = null;
    this.ifVisible();
    this.clearFromData();
  }
  //

  ifVisible() {
    this.initValue = null;
    this.isModalVisible = !this.isModalVisible;
    this.forceUpdate();
  }
  handleOk() {
    // this.ifVisible();
    let _this = this;
    const container: any = (this.instance as any) as HTMLDivElement;

    container
      .validateFields()
      .then((res) => {
        _this.setMenu(res);
        _this.ifVisible();
        //清空表单
        _this.clearFromData();
        _this.initValue = null;
      })
      .catch((err) => {
        console.log(err);
      });
  }
  //修改或者更新
  setMenu(menuIten) {
    for (let key in menuIten) {
      menuIten[key] = menuIten[key] ? menuIten[key] : null;
    }
    //如果有父级菜单
    if (menuIten["parentId"]) {
      for (let i = 0; i < this.listData.length; i++) {
        if (menuIten["parentId"] === this.listData[i]["treeId"]) {
          menuIten["levelIndex"] = this.listData[i]["levelIndex"];
        }
      }
    }
    switch (this.Mod) {
      case "add":
        this.setState({ loading: true });
        addMenu(JSON.stringify(menuIten))
          .then((res) => {
            let Data: any = res;
            if (Data.success) {
              this.init();
            }
          })
          .catch((err) => {
            console.log(err);
          });

        break;
      case "update":
        menuIten["treeId"] = this.initValue["treeId"];
        this.setState({ loading: true });
        updateMenu(JSON.stringify(menuIten))
          .then((res) => {
            let Data: any = res;
            if (Data.success) {
              this.init();
            }
          })
          .catch((err) => {
            console.log(err);
          });
        break;
      default:
        break;
    }
  }
  handleCancel() {
    this.ifVisible();
  }
  //清空表单
  clearFromData() {
    if (this.instance) {
      const container: any = (this.instance as any) as HTMLDivElement;
      container.setFieldsValue({
        rank: undefined,
        name: undefined,
        parentId: undefined,
        resIon: undefined,
        pathName: undefined,
        resUrl: undefined,
      });
    }
    this.initValue = null;
  }
}
interface AjaxData {
  code: number;
  success: boolean;
  message: string;
  data: any;
}
export default MenuTable;
